<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\WeChat\Pay;
/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Otc extends Backend
{
    
    /**
     * Otc模型对象
     * @var \app\admin\model\Otc
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Otc;
        $this->view->assign("orderTypeList", $this->model->getOrderTypeList());
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
        $this->view->assign("coinTypeList", $this->model->getCoinTypeList());
        $this->view->assign("buyTypeList", $this->model->getBuyTypeList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        //$this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->where($where)
                    ->where('order_type','neq',1)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->where($where)
                    ->where('order_type','neq',1)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            foreach ($list as $row) {
                if($row->collection_type){
                    if($row->collection_type==1){
                        $row->account_type ='微信';
                        $row->account_name = '';
                        $row->account_number ='';
                    }

                    // if($row->pay_account=='alipay'){
                    //     $row->account_type ='支付宝';
                    //     $pay_account = json_decode($pay_account,true);
                    //     $row->account_name = isset($pay_account['account_name'])?$pay_account['account_name']:'';
                    //     $row->account_number =isset($pay_account['account_number'])?$pay_account['account_number']:'';
                    //     $row->account_image =isset($pay_account['account_image'])?$pay_account['account_image']:'';
                    // }

                    if($row->collection_type==2){
                        
                        $pay_account = json_decode($row->collection_account,true);

                        $account_bank_name = isset($pay_account['account_bank_name'])?$pay_account['account_bank_name']:'';
                        $row->account_type =$account_bank_name;
                        $row->account_name = isset($pay_account['account_name'])?$pay_account['account_name']:'';
                        $row->account_number =isset($pay_account['account_number'])?$pay_account['account_number']:'';
                    }
                    
                }else{
                    $row->pay_account = '无';
                }
                
                
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * OTC卖出审核
     * @author M
     * @data             2020-02-11
     * @param  [type] $ids       [description]
     * @return [type]            [description]
     */
    public function edit($ids=null){
        $row = Db::name('user_order')
        ->where(['id'=>$ids,'order_type'=>3,'order_status'=>3])
        ->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $msg = '';
            $params = $this->request->post("row/a");
            $params = $this->preExcludeFields($params);
            $checktime =time();
            //订单状态:0=已撤销,1=已完成,2=售卖中,3=待审核,4=待支付
            $order_status = $params['order_status'];//
            Db::startTrans();
            try {
                //撤销OTC订单
                if($order_status ==0){
                    $remark = isset($params['remark'])?$params['remark']:'';
                    Db::name('user_order')
                    ->where(['id'=>$ids])
                    ->update(['order_status'=>0,'checktime'=>$checktime,'remark'=>$remark]); 

                    $findUser = Db::name('user')
                    ->where(['id'=>$row['user_id']])
                    ->lock(true)
                    ->find();

                    //退还卖出活动MU
                    Db::name('user')
                    ->where(['id'=>$row['user_id']])
                    ->update([
                    'active_mu' => Db::raw('active_mu+'.$row['coin_num']),
                    ]);

                    //来源:1=币币交易买入,2=币币交易卖出,3=OTC通道买入,4=OTC通道卖出,5=矿机收益,6=动态奖励,7=购买矿机,8=激活矿机,9=撤销订单
                    //资产类型:1=充值MU,2=活动MU,3=MQ
                    $user_balance_log['user_id']    = $row['user_id'];
                    $user_balance_log['amount']     = $row['coin_num'];
                    $user_balance_log['before']     = $findUser['active_mu'];
                    $user_balance_log['after']      = $findUser['active_mu']+$row['coin_num'];
                    $user_balance_log['remark']     = 'OTC通道卖出撤销';
                    $user_balance_log['type']       = 1;
                    $user_balance_log['log_type']   = 2;
                    $user_balance_log['source']     = 9;
                    $user_balance_log['createtime'] = time();
                    Db::name('user_balance_log')->insert($user_balance_log);
                    $msg = '撤销成功';
                }

                if($order_status ==4){
                    //微信打款
                    Db::name('user_order')
                    ->where(['id'=>$ids])
                    ->update(['order_status'=>4,'checktime'=>$checktime]); 
                }
                Db::commit();
                $this->success($msg);
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
    /**
     * 微信转账
     * @author M
     * @data             2020-02-21
     * @param  [type] $ids       [description]
     * @return [type]            [description]
     */
    public function transfers($ids=null){
        $row = Db::name('user_order')
        ->where(['id'=>$ids,'order_type'=>3,'order_status'=>4])
        ->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $config = wechat_config();
        $find = Db::name('third_party_user')
        ->where(['app_id'=>$config['appid'],'user_id'=>$row['user_id']])
        ->find();
        if($find){
            //微信转账到零钱
            try {
                $price = $row['sell_price']*100;
                $amount = intval($price);
                $wechat = new \WeChat\Pay($config);
                $options = [
                    'partner_trade_no' => $row['order_no'],
                    'openid'           => $find['openid'],
                    'check_name'       => 'NO_CHECK',
                    'amount'           => $amount,
                    'desc'             => '提现',
                    'spbill_create_ip' => '127.0.0.1',
                ];
                $result = $wechat->createTransfers($options);
                // print_r($result);
                // die;
                if ($result['result_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                    $return_info = json_encode($result);
                    $payment_time = strtotime($result['payment_time']);
                    $res =Db::name('user_order')
                    ->where(['order_no'=>$result['partner_trade_no']])
                    ->update(['order_status'=>1,'trade_no'=>$result['payment_no'],'paytime'=>$payment_time,'return_info'=>$return_info]); 
                    if($res){
                        $this->success('转账成功');
                    }
                }else{
                    $this->error($result['err_code_des']);
                }

            } catch (Exception $e) {
                //echo $e->getMessage() . PHP_EOL;
                 $this->error('转账失败');
            }
        }else{
            $this->error('该账号未绑定微信');
        }

    }

     /**
     * 确认打款
     * @author M
     * @data             2020-02-11
     * @param  [type] $ids       [description]
     * @return [type]            [description]
     */
    public function bank($ids=null){
        $row = Db::name('user_order')
        ->where(['id'=>$ids,'order_type'=>3,'order_status'=>4])
        ->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        //订单状态:0=已撤销,1=已完成,2=售卖中,3=待审核,4=待支付
        Db::startTrans();
        try {
            $res =Db::name('user_order')
            ->where(['id'=>$ids])
            ->update(['order_status'=>1,'paytime'=>time()]); 
            if($res){
                Db::commit();
                $this->success('确认成功');
            }
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    
}
